package com.fdd.furns.service.impl;

import com.fdd.furns.dao.FurnDAO;
import com.fdd.furns.dao.MemberDAO;
import com.fdd.furns.dao.OrderDAO;
import com.fdd.furns.dao.OrderItemDAO;
import com.fdd.furns.dao.impl.FurnDAOImpl;
import com.fdd.furns.dao.impl.MemberDAOImp;
import com.fdd.furns.dao.impl.OrderDAOImpl;
import com.fdd.furns.dao.impl.OrderItemDAOImpl;
import com.fdd.furns.pojo.*;
import com.fdd.furns.service.OrderService;
import com.mysql.cj.protocol.a.LocalDateTimeValueEncoder;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class OrderServiceImpl implements OrderService {
    OrderDAO orderDAO = new OrderDAOImpl();
    OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();



    @Override
    public String saveOrder(Cart cart, Integer memberId) {
        //将cart 转化为 Order
        //将cart 中的所有的CartItem 转化为 OrderItem

        String orderId = System.currentTimeMillis() + "" + memberId;
        Order order = new Order(orderId, LocalDateTime.now(), cart.getTotalPrice(), 0, memberId);
        orderDAO.saveOrder(order);

        //遍历cart 中的所有的CartItem ，转化为 OrderItem
        //调用OrderItemDAO 完成数据保存到数据库表 order_item

        HashMap<Integer, CartItem> items = cart.getItems();
        for (Integer id : items.keySet()) {
            CartItem cartItem = items.get(id);

            Furn furn = furnDAO.queryFurnById(id);
            if(cartItem.getCount() <= furn.getStock()){
                //调用OrderItemDAO 完成数据保存到数据库表 order_item
                OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getPrice(), cartItem.getCount(), cartItem.getTotalPrice(), orderId);
                orderItemDAO.saveOrderItem(orderItem);

                // 更新furn表中的库存和销量
                furn.setSales(furn.getSales() + cartItem.getCount());
                furn.setStock(furn.getStock() - cartItem.getCount());
                System.out.println("更新库存和销量");
                //更新到数据库表中
                furnDAO.updateFurn(furn);
            }


        }



        //清空购物车
        cart.clear();
        return orderId;

    }

    @Override
    public List<Order> getOrderByMemberId(Integer memberId) {
        return orderDAO.getOrderByMemberId(memberId);
    }
}

